// 初始化对话框
var CaseAddInfoDlg = {
    caseAddInfoData: {},
    zTreeInstance: null,
    validateFields: {}
};
//清除数据
CaseAddInfoDlg.clearData = function () {
    this.caseAddInfoData = {};
};
//设置对话框中的数据 @param key 数据的名称 @param val 数据的具体值
CaseAddInfoDlg.set = function (key, val) {
    this.caseAddInfoData[key] = (typeof value == "undefined") ? $("#" + key).val() : value;
    return this;
};
//设置对话框中的数据 @param key 数据的名称 @param val 数据的具体值
CaseAddInfoDlg.get = function (key) {
    return $("#" + key).val();
};
//关闭此对话框
CaseAddInfoDlg.close = function () {
    var index = parent.layer.getFrameIndex(window.name); //获取窗口索引
    parent.layer.close(index);
};
//收集数据
CaseAddInfoDlg.collectData = function () {
    this.set('id').set('personacct').set('szm').set('phone').set('nationality').set('nation').set('customerName').set('customerPhone').set('idCard').set('customerAge').set('birthday').set('insuranceState').set('saveStatus').set('selectionStatus').set('customerSex').set('medicalInsurance').set('applyOutpatient')
        .set('occupation').set('flag').set('createTime').set('updateTime').set('applyTime').set('address').set('personCondition').set('maritalStatus').set('medicalDepartment').set('medicalType').set('person_weight').set('personHeight').set('patientComplaints').set('presentIllness')
        .set('pastHistory').set('systemicDiseases').set('diagnosis').set('physicalExam').set('num').set('leftUp').set('rightUp').set('leftDown').set('rightDown')
        .set('treatmentAdvice').set('designThink').set('description').set('remarks').set('mark').set('treatmentSteps').set('personWeight')
        .set('code').set('caseType').set('hospitalizedTime').set('BMI').set('suppleExamResult').set('caseComment');
    var ratingItemsScoreList = [];
    $(".ratingItemsScore").each(function () {
        ratingItemsScoreList.push($(this).val()); //这里的value就是每一个input的value值~
    });
    this.caseAddInfoData['ratingItemsScore'] = ratingItemsScoreList.join("&&");//把一组检查的所有左上数组通过&&分割拼接成字符串 比如  1&&1
    var ratingItemsList = [];
    $(".ratingItems").each(function () {
        ratingItemsList.push($(this).val()); //这里的value就是每一个input的value值~
    });
    this.caseAddInfoData['ratingItems'] = ratingItemsList.join("&&");//把一组检查的所有左上数组通过&&分割拼接成字符串 比如  1&&1
    //添加牙位
    var leftUp1 = [];
    $(".therapeuticPositionLeftUp").each(function () {
        leftUp1.push($(this).val()); //这里的value就是每一个input的value值~
    });
    this.caseAddInfoData['leftUp1'] = leftUp1.join("&&");//把一组检查的所有左上数组通过&&分割拼接成字符串 比如  1&&1
    var leftDown1 = [];
    $(".therapeuticPositionRightUp").each(function () {
        leftDown1.push($(this).val()); //这里的value就是每一个input的value值~
    });
    this.caseAddInfoData['leftDown1'] = leftDown1.join("&&");//把一组检查的所有左上数组通过&&分割拼接成字符串 比如  1&&1
    var rightUp1 = [];
    $(".therapeuticPositionLeftDown").each(function () {
        rightUp1.push($(this).val()); //这里的value就是每一个input的value值~
    });
    this.caseAddInfoData['rightUp1'] = rightUp1.join("&&");//把一组检查的所有左上数组通过&&分割拼接成字符串 比如  1&&1
    var rightDown1 = [];
    $(".therapeuticPositionRightDown").each(function () {
        rightDown1.push($(this).val()); //这里的value就是每一个input的value值~
    });
    this.caseAddInfoData['rightDown1'] = rightDown1.join("&&");//把一组检查的所有左上数组通过&&分割拼接成字符串 比如  1&&1
    var treatmentSteps = [];
    $(".treatmentSteps").each(function () {
        treatmentSteps.push($(this).val()); //这里的value就是每一个input的value值~
    });
    this.caseAddInfoData['treatmentSteps'] = treatmentSteps.join("&&");//把一组检查的所有左上数组通过&&分割拼接成字符串 比如  1&&1
};
//验证数据是否为空
CaseAddInfoDlg.validate = function () {
    $('#caseAddInfoForm').data("bootstrapValidator").resetForm();
    $('#caseAddInfoForm').bootstrapValidator('validate');
    return $("#caseAddInfoForm").data('bootstrapValidator').isValid();
};

//添加暂存病例
CaseAddInfoDlg.storage = function (obj) {
    this.clearData();
    this.collectData();
    var ajax = new $ax(Feng.ctxPath + "/caseSelectionUpload/storage", function (data) {
        Feng.success("添加成功!");
        window.parent.CaseSelectionUpload.search();
        CaseAddInfoDlg.close()
    }, function (data) {
        Feng.error("添加失败!" + data.responseJSON.message + "!");
    });
    ajax.set(this.caseAddInfoData);
    ajax.start();
};

CaseAddInfoDlg.getCaseQRCode = function (obj) {
    var id=document.getElementById("id").value;
    $.ajax({
        type: "POST",
        url:  Feng.ctxPath + "/caseSelectionUpload/getCaseQRCode" ,
        data: {
            id:id
        },
        dataType: "json",
        success: function (data) {
            var index = layer.open({
                type: 2,
                title: '病例评分二维码',
                area: ['40%', '50%'], //宽高
                fix: true, //不固定
                maxmin: true,
                content: Feng.ctxPath + '/caseSelectionVote/to_caseQRCode',
            });
            this.layerIndex = index;
        }
    });
};
//添加暂存病例
CaseAddInfoDlg.selectionstorage = function (obj) {
    this.clearData();
    this.collectData();
    var ajax = new $ax(Feng.ctxPath + "/caseSelection/selectionstorage", function (data) {
        Feng.success("添加成功!");
        window.parent.CaseSelection.search();
        CaseAddInfoDlg.close()
    }, function (data) {
        Feng.error("添加失败!" + data.responseJSON.message + "!");
    });
    ajax.set(this.caseAddInfoData);
    ajax.start();
};
//添加暂存病例
CaseAddInfoDlg.selectionsubmitTo = function (obj) {
    if (confirm("确定提交之后评分不能修改")) {
        this.clearData();
        this.collectData();
        var ajax = new $ax(Feng.ctxPath + "/caseSelection/selectionsubmitTo", function (data) {
            Feng.success("添加成功!");
            window.parent.CaseSelection.search();
            CaseAddInfoDlg.close()
        }, function (data) {
            Feng.error("添加失败!" + data.responseJSON.message + "!");
        });
        ajax.set(this.caseAddInfoData);
        ajax.start();
    }
};

CaseAddInfoDlg.goback = function (obj) {
    var id = document.getElementById("id").value;
    var index = layer.open({
        type: 2,
        title: '病例评分',
        area: ['40%', '50%'], //宽高
        fix: true, //不固定
        maxmin: true,
        content: Feng.ctxPath + '/caseSelection/to_goback/' + id
    });
    this.layerIndex = index;
};

//添加提交病例
CaseAddInfoDlg.submitTo = function (obj) {
    this.clearData();
    this.collectData();
    var customerName = $("#customerName").val();
    if (customerName == null || customerName == "") {
        layer.alert("请输入患者姓名！");
        return false;
    }
    var customerAge = $("#customerAge").val();
    if (customerAge == null || customerAge == "") {
        layer.alert("请输入年龄！");
        return false;
    }
    var customerSex = $("#customerSex").val();
    if (customerSex == null || customerSex == "") {
        layer.alert("请输入性别！");
        return false;
    }
    var medicalDepartment = $("#medicalDepartment").val();
    if (medicalDepartment == null || medicalDepartment == "") {
        layer.alert("请输入就诊科室！");
        return false;
    }
    var patientComplaints = $("#patientComplaints").val();
    if (patientComplaints == null || patientComplaints == "") {
        layer.alert("请输入患者主诉！");
        return false;
    }
    var presentIllness = $("#presentIllness").val();
    if (presentIllness == null || presentIllness == "") {
        layer.alert("请输入现病史！");
        return false;
    }
    var pastHistory = $("#pastHistory").val();
    if (pastHistory == null || pastHistory == "") {
        layer.alert("请输入既往史！");
        return false;
    }
    var systemicDiseases = $("#systemicDiseases").val();
    if (systemicDiseases == null || systemicDiseases == "") {
        layer.alert("请输入系统疾病史！");
        return false;
    }
    var diagnosis = $("#diagnosis").val();
    if (diagnosis == null || diagnosis == "") {
        layer.alert("请输入诊断！");
        return false;
    }
    var suppleExamResult = $("#suppleExamResult").val();
    if (suppleExamResult == null || suppleExamResult == "") {
        layer.alert("请输入辅助检查结果！");
        return false;
    }
    var hospitalizedTime = $("#hospitalizedTime").val();
    if (hospitalizedTime == null || hospitalizedTime == "") {
        layer.alert("请输入初诊时间！");
        return false;
    }
    var avatar4PreId = $("#avatar4PreId").html();
    if (avatar4PreId.trim() == null || avatar4PreId.trim() == "") {
        layer.alert("请输入术前口内照！");
        return false;
    }
    var avatar9PreId = $("#avatar9PreId").html();
    if (avatar9PreId.trim() == null || avatar9PreId.trim() == "") {
        layer.alert("请输入术中口内照！");
        return false;
    }
    var avatar10PreId = $("#avatar10PreId").html();
    if (avatar10PreId.trim() == null || avatar10PreId.trim() == "") {
         layer.alert("请输入术后口内照！");
         return false;
    }
    var avatar8PreId = $("#avatar8PreId").html();
    if (avatar8PreId.trim() == null || avatar8PreId.trim() == "") {
        layer.alert("请输入术后口内照！");
        return false;
    }
    var avatarPreId = $("#avatarPreId").html();
    if (avatarPreId.trim() == null || avatarPreId.trim() == "") {
        layer.alert("请输入辅助检查中牙片照！");
        return false;
    }
    var avatarPreId = $("#avatarPreId").html();
    if (avatarPreId.trim() == null || avatarPreId.trim() == "") {
        layer.alert("请输入辅助检查中牙片照！");
        return false;
    }
    var avatar5PreId = $("#avatar5PreId").html();
    if (avatar5PreId.trim() == null || avatar5PreId.trim() == "") {
        layer.alert("请输入术后跟踪中牙片照！");
        return false;
    }
    if (confirm("确定提交之后不能修改和删除病例")) {
        var ajax = new $ax(Feng.ctxPath + "/caseSelectionUpload/submitTo", function (data) {
            if(data==10001){
                Feng.success("提交成功!");
                window.parent.CaseSelectionUpload.search();
                CaseAddInfoDlg.close()
            }else{
                alert("每个参赛者最多投递" + data + "份参选病例，您已达到最大投递限额，如有需要请联系举办方！");
                return;
            }
        }, function (data) {
            Feng.error("提交失败!" + data.responseJSON.message + "!");
        });
        ajax.set(this.caseAddInfoData);
        ajax.start();
    }
};
//暂存修改病例
CaseAddInfoDlg.updateStorage = function (obj) {
    this.clearData();
    this.collectData();
    var ajax = new $ax(Feng.ctxPath + "/caseSelectionUpload/updatestorage", function (data) {
        Feng.success("修改成功!");
        window.parent.CaseSelectionUpload.search();
        CaseAddInfoDlg.close()
    }, function (data) {
        Feng.error("修改失败!" + data.responseJSON.message + "!");
    });
    ajax.set(this.caseAddInfoData);
    ajax.start();
};

CaseAddInfoDlg.updateSubmitTo = function (obj) {
    this.clearData();
    this.collectData();
    var customerName = $("#customerName").val();
    if (customerName == null || customerName == "") {
        layer.alert("请输入患者姓名！");
        return false;
    }
    var customerAge = $("#customerAge").val();
    if (customerAge == null || customerAge == "") {
        layer.alert("请输入年龄！");
        return false;
    }
    var customerSex = $("#customerSex").val();
    if (customerSex == null || customerSex == "") {
        layer.alert("请输入性别！");
        return false;
    }
    var patientComplaints = $("#patientComplaints").val();
    if (patientComplaints == null || patientComplaints == "") {
        layer.alert("请输入患者主诉！");
        return false;
    }
    var presentIllness = $("#presentIllness").val();
    if (presentIllness == null || presentIllness == "") {
        layer.alert("请输入现病史！");
        return false;
    }
    var pastHistory = $("#pastHistory").val();
    if (pastHistory == null || pastHistory == "") {
        layer.alert("请输入既往史！");
        return false;
    }
    var systemicDiseases = $("#systemicDiseases").val();
    if (systemicDiseases == null || systemicDiseases == "") {
        layer.alert("请输入系统疾病史！");
        return false;
    }
    var diagnosis = $("#diagnosis").val();
    if (diagnosis == null || diagnosis == "") {
        layer.alert("请输入诊断！");
        return false;
    }
    var suppleExamResult = $("#suppleExamResult").val();
    if (suppleExamResult == null || suppleExamResult == "") {
        layer.alert("请输入辅助检查结果！");
        return false;
    }
    var hospitalizedTime = $("#hospitalizedTime").val();
    if (hospitalizedTime == null || hospitalizedTime == "") {
        layer.alert("请输入初诊时间！");
        return false;
    }
    var avatar4PreId = $("#avatar4PreId").html();
    if (avatar4PreId.trim() == null || avatar4PreId.trim() == "") {
        layer.alert("请输入术前口内照！");
        return false;
    }
    var avatar9PreId = $("#avatar9PreId").html();
    if (avatar9PreId.trim() == null || avatar9PreId.trim() == "") {
        layer.alert("请输入术中口内照！");
        return false;
    }
    var avatar10PreId = $("#avatar10PreId").html();
    if (avatar10PreId.trim() == null || avatar10PreId.trim() == "") {
         layer.alert("请输入术后口内照！");
         return false;
    }
    var avatar8PreId = $("#avatar8PreId").html();
    if (avatar8PreId.trim() == null || avatar8PreId.trim() == "") {
        layer.alert("请输入术后口内照！");
        return false;
    }
    var avatarPreId = $("#avatarPreId").html();
    if (avatarPreId.trim() == null || avatarPreId.trim() == "") {
        layer.alert("请输入辅助检查中牙片照！");
        return false;
    }
    var avatar5PreId = $("#avatar5PreId").html();
    if (avatar5PreId.trim() == null || avatar5PreId.trim() == "") {
        layer.alert("请输入术后跟踪中牙片照！");
        return false;
    }
    if (confirm("确定提交之后病例不能修改")) {
        var ajax = new $ax(Feng.ctxPath + "/caseSelectionUpload/updateSubmitTo", function (data) {
            if(data==10001){
                Feng.success("提交成功!");
                window.parent.CaseSelectionUpload.search();
                CaseAddInfoDlg.close()
            }else{
                alert("每个参赛者最多投递" + data + "份参选病例，您已达到最大投递限额，如有需要请联系举办方！");
                return;
            }
        }, function (data) {
            Feng.error("提交失败!" + data.responseJSON.message + "!");
        });
        ajax.set(this.caseAddInfoData);
        ajax.start();
    }
}
// 微信返回
CaseAddInfoDlg.patient = function () {
    if ($("#numValue").val() == '1') {
        window.location.href = Feng.ctxPath + "/weixin/index";
    } else if ($("#numValue").val() == '2') {
        window.location.href = Feng.ctxPath + "/reservation/market_patient";
    }
};
//病例评分
CaseAddInfoDlg.caseScore = function () {
    var id = document.getElementById("id").value;
    var index = layer.open({
        type: 2,
        title: '病例评分',
        area: ['40%', '50%'], //宽高
        fix: true, //不固定
        maxmin: true,
        content: Feng.ctxPath + '/caseSelectionUpload/doctor_caseScore/' + id
    });
    this.layerIndex = index;
};
//病例标签
CaseAddInfoDlg.caseMarking = function () {
    var index = layer.open({
        type: 2,
        title: '病例标签',
        area: ['40%', '50%'], //宽高
        fix: true, //不固定
        maxmin: true,
        content: Feng.ctxPath + '/caseSelectionUpload/doctor_caseMarking'
    });
    this.layerIndex = index;
};
//初始化数据
CaseAddInfoDlg.initData = function () {
    var seletecustomerSex = $('#customerSexValue').val();
    if (seletecustomerSex != "") {
        $("#customerSex option[value=" + seletecustomerSex + "]").attr("selected", "selected");
    }
    var seletemaritalStatus = $('#maritalStatusValue').val();
    if (seletemaritalStatus != "") {
        $("#maritalStatus option[value=" + seletemaritalStatus + "]").attr("selected", "selected");
    }
    var seletenationality = $('#nationalityValue').val();
    if (seletenationality != "") {
        $("#nationality option[value=" + seletenationality + "]").attr("selected", "selected");
    }
    var seleteinsuranceState = $('#insuranceStateValue').val();
    if (seleteinsuranceState != "") {
        $("#insuranceState option[value=" + seleteinsuranceState + "]").attr("selected", "selected");
    }
    var seletemedicalType = $('#medicalTypeValue').val();
    if (seletemedicalType != "") {
        $("#medicalType option[value=" + seletemedicalType + "]").attr("selected", "selected");
    }
};

function checkDate() {
    var date = new Date();
    date.setDate(date.getDate() - 1);
    var now = date.valueOf();
    var time = new Date($("#appointmentArrivalTime").val()).valueOf();
    if (now < time) {
        layer.alert("请检查初诊时间！");
    }
};

var avatarUp,avatarUp1,avatarUp2,avatarUp3,avatarUp4,avatarUp5,avatarUp6,avatarUp7,avatarUp8,avatarUp9,avatarUp10 = "";
function iconTypeChange() {
    avatarUp = new $IconUpload("avatar");
    avatarUp.initIcon();
    avatarUp1 = new $IconUpload("avatar1");
    avatarUp1.initIcon();
    avatarUp2 = new $IconUpload("avatar2");
    avatarUp2.initIcon();
    avatarUp3 = new $IconUpload("avatar3");
    avatarUp3.initIcon();
    avatarUp4 = new $IconUpload("avatar4");
    avatarUp4.initIcon();
    avatarUp5 = new $IconUpload("avatar5");
    avatarUp5.initIcon();
    avatarUp6 = new $IconUpload("avatar6");
    avatarUp6.initIcon();
    avatarUp7 = new $IconUpload("avatar7");
    avatarUp7.initIcon();
    avatarUp8 = new $IconUpload("avatar8");
    avatarUp8.initIcon();
    avatarUp9 = new $IconUpload("avatar9");
    avatarUp9.initIcon();
    avatarUp10 = new $IconUpload("avatar10");
    avatarUp10.initIcon();
}
$(".add").click(function () {
    var mode = $(this).parent().children().eq(1).clone();
    $(mode).find('.treatmentSteps,.toothNone').val("");
    $(this).before(mode);
});
$(".consulFormation").on('click', '.deleteBtn', function () {
    var index = $(this).parents('.treatmentStepsContent').index();
    if (index != 1) {
        $(this).parents('.treatmentStepsContent').remove()
    }
});

var imagePathText = '';
var imagePathId = '';

$(function () {
    Feng.initValidator("caseAddInfoForm", CaseAddInfoDlg.validateFields);
    CaseAddInfoDlg.initData();
    $(".modify").attr("readOnly", "true");
    $(".select_styles").attr("disabled", "disabled");
    //输入年龄出生日期显示
    $("#customerAge").on('input', function () {
        var date = new Date();
        var currentYear = date.getFullYear() - $("#customerAge").val();
        $("#birthday").val(currentYear + "-01-01")
    });
    $("#birthday").on("input", function () {
        var resbirthday = /^(19\d\d|20\d\d)[-/ ](0\d|1[0-2])[-/ ](0\d|[1-2]\d|30|31)$/;
        var birthday = $("#birthday").val();
        if (birthday.length > 0 && birthday.length < 4) {
        } else if (birthday.length >= 4 && birthday.length < 10) {
            var s = birthday.substring(0, 4);
            if (!isNaN(s)) {
                var data = new Date();
                $("#customerAge").val(data.getFullYear() - s)
            }
        } else {
            if (resbirthday.test(birthday)) {
                var birthDayTime = new Date(birthday).getTime();
                var nowTime = new Date().getTime();
                $("#customerAge").val(Math.ceil((nowTime - birthDayTime) / 31536000000))
            } else {
                Feng.error("请输入正确的格式！")
            }
        }
    });
    $(document).on('click', '.cp_img_delete', function () {
        var that = this;
        var id = $(that).parent().attr("id");
        var customerId = $("id").val();
        $.ajax({
            url: Feng.ctxPath + "/caseSelectionUpload/delteProcess",
            type: "post",
            data: {
                "id": id,
                "customerId": customerId
            },
            success: function (data) {
                $(that).parent().hide();
                Feng.success("删除成功！");
            },
            error: function (data) {
                alert("删除失败！");
            }
        })
    });

    $(document).on('click', '.imagePath', function () {
        var _this = $(this);//将当前的pimg元素作为_this传入函数
        imgShow("#outerdiv", "#innerdiv", "#bigimg", _this);
    });

    iconTypeChange();

    function imgShow(outerdiv, innerdiv, bigimg, _this) {
        var src = _this.attr("src");//获取当前点击的pimg元素中的src属性
        imagePathId = _this.parent().attr("id")
        imagePathText = _this.siblings('span').text()
        $(bigimg).attr("src", src);//设置#bigimg元素的src属性
        if(imagePathText === "术前"){
            $("#innerdiv").find('.dashed-box,.shuzhong,.shuhou').hide();
            $("#innerdiv").find('.shuqian').show();
        }else if(imagePathText === "术中"){
            $("#innerdiv").find('.dashed-box,.shuqian,.shuhou').hide();
            $("#innerdiv").find('.shuzhong').show();
        }else if(imagePathText === "术后"){
            $("#innerdiv").find('.dashed-box,.shuqian,.shuzhong').hide();
            $("#innerdiv").find('.shuhou').show();
        }else {
            $("#innerdiv").find('.questionBox').hide();
        }
        /*获取当前点击图片的真实大小，并显示弹出层及大图*/
        $("<img/>").attr("src", src).load(function () {
            var windowW = $(window).width();//获取当前窗口宽度
            var windowH = $(window).height();//获取当前窗口高度
            var realWidth = this.width;//获取图片真实宽度
            var realHeight = this.height;//获取图片真实高度
            var imgWidth, imgHeight;
            var scale = 0.8;//缩放尺寸，当图片真实宽度和高度大于窗口宽度和高度时进行缩放

            if (realHeight > windowH * scale) {//判断图片高度
                imgHeight = windowH * scale;//如大于窗口高度，图片高度进行缩放
                imgWidth = imgHeight / realHeight * realWidth;//等比例缩放宽度
                if (imgWidth > windowW * scale) {//如宽度扔大于窗口宽度
                    imgWidth = windowW * scale;//再对宽度进行缩放
                }
            } else if (realWidth > windowW * scale) {//如图片高度合适，判断图片宽度
                imgWidth = windowW * scale;//如大于窗口宽度，图片宽度进行缩放
                imgHeight = imgWidth / realWidth * realHeight;//等比例缩放高度
            } else {//如果图片真实高度和宽度都符合要求，高宽不变
                imgWidth = realWidth;
                imgHeight = realHeight;
            }
            $(bigimg).css("width", imgWidth);//以最终的宽度对图片缩放

            var w = (windowW - imgWidth) / 2;//计算图片与窗口左边距
            var h = (windowH - imgHeight) / 2;//计算图片与窗口上边距
            $(innerdiv).css({"top": h, "left": w});//设置#innerdiv的top和left属性
            $(outerdiv).fadeIn("fast");//淡入显示#outerdiv及.pimg
        });

        $(outerdiv).click(function (e) {//再次点击淡出消失弹出层
            $(this).fadeOut("fast");
            // $("#innerdiv").find('.questionBox,.dashed-box').remove();
        });
    }


    for(var i=0 ; i<$(".btnBox").find(".ratingItemsScore").length ; i++){
        if($(".btnBox").find(".ratingItemsScore").eq(i).val() == ""){
            $(".btnBox").find(".ratingItemsScore").eq(i).val(0)
        }
    }
});

window.onload = function() {
    function stopDefault(e) {
        if(e && e.preventDefault)
            e.preventDefault();
        else
            window.event.returnValue = false;
        return false;
    }
    $("#innerdiv").click(function (e) {
        e.stopPropagation();
    });
    function oBox() {
        var wId = "w";
        var index = 0;
        var target = null;
        var startX = 0, startY = 0;
        var dragging = false;
        var startL = 0, startT = 0, boxHeight = 0, boxWidth = 0;
        var boxObj = document.getElementById("innerdiv");
        var newMarkPos = {
            "left": startL,////按下时鼠标距离的左边的距离
            "top": startT////按下时鼠标距离的上边的距离
        };
        //鼠标点击
        boxObj.onmousedown = function(e) {
            dragging = true;
            var e = window.event || e;
            target = e.target || e.srcElement; //获取document 对象的引用
            //e.pageY，e.pageX兼容
            if(target.src) {stopDefault(e)}
            var frame = $("#innerdiv");
            var referenceSize = {
                "pos": frame.offset(),
                "width": frame.outerWidth(),
                "height": frame.outerHeight()
            };
            var scrollTop = boxObj.scrollTop;
            var scrollLeft = boxObj.scrollLeft;
            var ePageX = e.clientX + scrollLeft;
            var ePageY = e.clientY + scrollTop;
            //按下时鼠标距离页面的距离
            startX = ePageX;
            startY = ePageY;
            //按下时鼠标距离的左边和上边的距离
            startL = startX - referenceSize.pos.left;
            startT = startY - referenceSize.pos.top;
            index++;
            // 如果鼠标在 box 上被按下
            if(target.className.match(/del-box/i)) {
                // 允许拖动
                dragging = false;
                // 设置当前 box 的 id 为 moving_box
                var movingBox = document.getElementById("moving_box")
                if(movingBox !== null) {
                    movingBox.removeAttribute("id");
                }
                target.id = "moving_box";
                removeBox(target);
            } else {
                if(imagePathText === "术前"){
                    $("#innerdiv").find('.dashed-box,.shuqian').remove();
                }else if(imagePathText === "术中"){
                    $("#innerdiv").find('.dashed-box,.shuzhong').remove();
                }else if(imagePathText === "术后"){
                    $("#innerdiv").find('.dashed-box,.shuhou').remove();
                }else {
                    $("#innerdiv").find('.dashed-box,.qita').remove();
                }
                var div = document.createElement("div");
                div.id = wId + index;
                div.className = "dashed-box";
                boxObj.appendChild(div);
                div = null;
            }
        };
        //鼠标离开
        boxObj.onmouseup = function(e) {
            var e = window.event || e;
            if(boxWidth >= 5 || boxHeight >= 5) {
                boxObj.removeChild(dragBox(wId + index));
                index++;
                var div = document.createElement("div");
                var spanObj = document.createElement("span");
                var spanObjTow = document.createElement("span");
                spanObj.className = 'del-box';
                spanObj.innerHTML = parseInt(newMarkPos.left) + "," + parseInt(newMarkPos.top);
                spanObjTow.className = 'delBoxTow';
                spanObjTow.innerHTML = parseInt(newMarkPos.left + boxWidth) + "," + parseInt(newMarkPos.top + boxHeight);
                var initialCoordinate = parseInt(newMarkPos.left) + "," + parseInt(newMarkPos.top);
                var endpointCoordinate = parseInt(newMarkPos.left + boxWidth) + "," + parseInt(newMarkPos.top + boxHeight);
                div.appendChild(spanObj);
                div.appendChild(spanObjTow);
                if(imagePathText === "术前"){
                    div.className = "questionBox questionBorder shuqian";
                }else if(imagePathText === "术中"){
                    div.className = "questionBox questionBorder shuzhong";
                }else if(imagePathText === "术后"){
                    div.className = "questionBox questionBorder shuhou";
                }else {
                    div.className = "questionBox questionBorder qita";
                }
                div.style.left = newMarkPos.left + "px";
                div.style.top = newMarkPos.top + "px";
                div.style.width = boxWidth + "px";
                div.style.height = boxHeight + "px";
                boxObj.appendChild(div);
                div = null;
                boxWidth = 0;
                boxHeight = 0;
                if(imagePathText === "术前"){
                    $("#imagePathPreoperative").val(imagePathId +";"+ imagePathText + ";" + initialCoordinate + ";" + endpointCoordinate)
                }
                if(imagePathText === "术中"){
                    $("#imagePathIntraoperative").val(imagePathId +";"+ imagePathText + ";" + initialCoordinate + ";" + endpointCoordinate)
                }
                if(imagePathText === "术后"){
                    $("#imagePathPostoperative").val(imagePathId +";"+ imagePathText + ";" + initialCoordinate + ";" + endpointCoordinate)
                }
            } else {
                if(dragging) {
                    boxObj.removeChild(dragBox(wId + index));
                }
            }
            dragging = false;
        };
        //鼠标移动
        boxObj.onmousemove = function(e) {
            var e = window.event || e;
            stopDefault(e);
            if(dragging) {
                var scrollTop = boxObj.scrollTop;
                var scrollLeft = boxObj.scrollLeft;
                var ePX = e.clientX + scrollLeft;
                var ePY = e.clientY + scrollTop;
                var disW = ePX - startX;
                var disH = ePY - startY;
                var L = startL + disW;
                var T = startT + disH;
                if(disW > 0) {
                    if(L >= 0) {
                        boxWidth = disW
                    }
                    newMarkPos.left = startL;
                } else {
                    if(L <= 0) {
                        L = 0;
                        boxWidth = startL;
                    }
                    boxWidth = (startL - L);
                    newMarkPos.left = L;
                }
                if(disH > 0) {
                    if(T >= 0) {
                        boxHeight = disH
                    }
                    newMarkPos.top = startT;
                } else {
                    if(T <= 0) {
                        T = 0;
                        boxHeight = startT;
                    }
                    boxHeight = (startT - T)
                    newMarkPos.top = T;
                }
                dragBox(wId + index).style.left = newMarkPos.left + "px";
                dragBox(wId + index).style.top = newMarkPos.top + "px";
                dragBox(wId + index).style.width = Math.abs(boxWidth) + "px";
                dragBox(wId + index).style.height = Math.abs(boxHeight) + "px";
                stopDefault(e)
            }
        };
        var dragBox = function(id) {
            return document.getElementById(id);
        }
    };
    oBox();
    function removeBox(obj) {
        if(obj) {
            var innerdiv = document.getElementById('innerdiv');
            if(obj.className == 'del-box') {
                var objId = document.getElementById(obj.id);
                innerdiv.removeChild(objId.parentNode);
            } else {
                alert(123)
            }
        }
    };
};

var tips;
var toothId;
$(document).on('click', '.toothBox', function (e) {
    e.stopPropagation();
    $(".toothBox").removeClass('tips');
    $(this).addClass('tips');
    toothId = $(this).attr("id");
    var leftUpNum = $(this).find('.leftUp').val();
    var rightUpNum = $(this).find('.rightUp').val();
    var leftDownNum = $(this).find('.leftDown').val();
    var rightDownNum = $(this).find('.rightDown').val();
    tips = layer.open({
        type: 4,
        tips: [1, '#ffffff'],
        closeBtn: 0,
        area: ['auto', 'auto'],
        content: ['<div>' + $("#noneBox").html() + '</div>', '.tips'],
        success: function (layero, index) {
            if (leftUpNum.length > 0) {
                for (var w = 0; w < $(layero).find('.toothTopLeft>span').length; w++) {
                    for (var i = 0; i < leftUpNum.length; i++) {
                        if ($(layero).find('.toothTopLeft>span').eq(w).find('span').text() == leftUpNum.substring(i, i + 1)) {
                            $(layero).find('.toothTopLeft>span').eq(w).find('span').addClass('spanStyle');
                        }
                    }
                }
            }
            if (rightUpNum.length > 0) {
                for (var w = 0; w < $(layero).find('.toothTopRight>span').length; w++) {
                    for (var i = 0; i < rightUpNum.length; i++) {
                        if ($(layero).find('.toothTopRight>span').eq(w).find('span').text() == rightUpNum.substring(i, i + 1)) {
                            $(layero).find('.toothTopRight>span').eq(w).find('span').addClass('spanStyle');
                        }
                    }
                }
            }
            if (leftDownNum.length > 0) {
                for (var w = 0; w < $(layero).find('.toothBottomLeft>span').length; w++) {
                    for (var i = 0; i < leftDownNum.length; i++) {
                        if ($(layero).find('.toothBottomLeft>span').eq(w).find('span').text() == leftDownNum.substring(i, i + 1)) {
                            $(layero).find('.toothBottomLeft>span').eq(w).find('span').addClass('spanStyle');
                        }
                    }
                }
            }
            if (rightDownNum.length > 0) {
                for (var w = 0; w < $(layero).find('.toothBottomRight>span').length; w++) {
                    for (var i = 0; i < rightDownNum.length; i++) {
                        if ($(layero).find('.toothBottomRight>span').eq(w).find('span').text() == rightDownNum.substring(i, i + 1)) {
                            $(layero).find('.toothBottomRight>span').eq(w).find('span').addClass('spanStyle');
                        }
                    }
                }
            }
        }
    });
});

$(document).click(function () {
    layer.close(tips)
});

$(document).on('click', '.tipsUl>li', function (e) {
    e.stopPropagation();
    $(this).addClass('tipsLi').siblings().removeClass('tipsLi');
    if ($(this).index() == 0) {
        $(this).parent().siblings().children('#permanent').show().siblings().hide()
    } else if ($(this).index() == 1) {
        $(this).parent().siblings().children('#deciduous').show().siblings().hide()
    }
});

$(document).on('click', '.toothTopLeft>span', function (e) {
    e.stopPropagation();
    var arr = [];
     var toothValue = $(this).text();
    if (!$(this).children().hasClass('spanStyle')) {
        var inputValue = $(".tips .leftUp").val().replace(toothValue, "");
        for (var i = 0; i < inputValue.length; i++) {
            arr.push(inputValue.substring(i, i + 1));
        }
        for (var i = arr.length - 1; i >= 0; i--) {
            for (var j = 0; j < i; j++) {
                if (arr[j + 1] > arr[j]) {
                    var change = arr[j + 1];
                    arr[j + 1] = arr[j];
                    arr[j] = change
                }
            }
        };
        var str = "";
        for (var i = 0; i < arr.length; i++) {
            str += arr[i]
        }
        $(".tips .leftUp").val(str);
        $(this).children().removeClass('spanStyle');
    } else {
        console.log(1);
        console.log(toothValue);
        $(this).children().addClass('spanStyle');
        var add = $(".tips .leftUp").val() + toothValue;
        for (var d = 0; d < add.length; d++) {
            arr.push(add.substring(d, d + 1));
        }
        for (var i = arr.length - 1; i >= 0; i--) {
            for (var j = 0; j < i; j++) {
                if (arr[j + 1] > arr[j]) {
                    var change = arr[j + 1];
                    arr[j + 1] = arr[j];
                    arr[j] = change
                }
            }
        };
        var str = "";
        for (var i = 0; i < arr.length; i++) {
            str += arr[i]
        }
        $(".tips .leftUp").val(str);
    }
});

$(document).on('click', '.toothTopRight>span', function (e) {
    e.stopPropagation();
    var arr = [];
    var toothValue = $(this).text();
    if (!$(this).children().hasClass('spanStyle')) {
        var inputValue = $(".tips .rightUp").val().replace(toothValue, "");
        for (var i = 0; i < inputValue.length; i++) {
            arr.push(inputValue.substring(i, i + 1));
        }
        for (var i = arr.length - 1; i >= 0; i--) {
            for (var j = 0; j < i; j++) {
                if (arr[j + 1] < arr[j]) {
                    var change = arr[j + 1];
                    arr[j + 1] = arr[j];
                    arr[j] = change
                }
            }
        };
        var str = "";
        for (var i = 0; i < arr.length; i++) {
            str += arr[i]
        }
        $(".tips .rightUp").val(str);
        $(this).children().removeClass('spanStyle');
    } else {
        $(this).children().addClass('spanStyle');
        var add = $(".tips .rightUp").val() + toothValue;
        for (var d = 0; d < add.length; d++) {
            arr.push(add.substring(d, d + 1));
        }
        for (var i = arr.length - 1; i >= 0; i--) {
            for (var j = 0; j < i; j++) {
                if (arr[j + 1] < arr[j]) {
                    var change = arr[j + 1];
                    arr[j + 1] = arr[j];
                    arr[j] = change
                }
            }
        };
        var str = "";
        for (var i = 0; i < arr.length; i++) {
            str += arr[i]
        }
        $(".tips .rightUp").val(str);
    }
});

$(document).on('click', '.toothBottomLeft>span', function (e) {
    e.stopPropagation();
      var arr = [];
      var toothValue = $(this).text();
      if (!$(this).children().hasClass('spanStyle')) {
          var inputValue = $(".tips .leftDown").val().replace(toothValue, "");
          for (var i = 0; i < inputValue.length; i++) {
              arr.push(inputValue.substring(i, i + 1));
          }
          for (var i = arr.length - 1; i >= 0; i--) {
              for (var j = 0; j < i; j++) {
                  if (arr[j + 1] < arr[j]) {
                      var change = arr[j + 1];
                      arr[j + 1] = arr[j];
                      arr[j] = change
                  }
              }
          }
          var str = "";
          for (var i = 0; i < arr.length; i++) {
              str += arr[i]
          }
          $(".tips .leftDown").val(str);
          $(this).children().removeClass('spanStyle');
      } else {
          $(this).children().addClass('spanStyle');
          var add = $(".tips .leftDown").val() + toothValue;
          for (var d = 0; d < add.length; d++) {
              arr.push(add.substring(d, d + 1));
          }
          for (var i = arr.length - 1; i >= 0; i--) {
              for (var j = 0; j < i; j++) {
                  if (arr[j + 1] < arr[j]) {
                      var change = arr[j + 1];
                      arr[j + 1] = arr[j];
                      arr[j] = change
                  }
              }
          }
          var str = "";
          for (var i = 0; i < arr.length; i++) {
              str += arr[i]
          }
          $(".tips .leftDown").val(str);
      }
});

$(document).on('click', '.toothBottomRight>span', function (e) {
    e.stopPropagation();
    var arr = [];
    var toothValue = $(this).text();
    if (!$(this).children().hasClass('spanStyle')) {
        var inputValue = $(".tips .rightDown").val().replace(toothValue, "");
        for (var i = 0; i < inputValue.length; i++) {
            arr.push(inputValue.substring(i, i + 1));
        }
        for (var i = arr.length - 1; i >= 0; i--) {
            for (var j = 0; j < i; j++) {
                if (arr[j + 1] < arr[j]) {
                    var change = arr[j + 1];
                    arr[j + 1] = arr[j];
                    arr[j] = change
                }
            }
        }
        var str = "";
        for (var i = 0; i < arr.length; i++) {
            str += arr[i]
        }
        $(".tips .rightDown").val(str);
        $(this).children().removeClass('spanStyle');
    } else {
        $(this).children().addClass('spanStyle');
        var add = $(".tips .rightDown").val() + toothValue;
        for (var d = 0; d < add.length; d++) {
            arr.push(add.substring(d, d + 1));
        }
        for (var i = arr.length - 1; i >= 0; i--) {
            for (var j = 0; j < i; j++) {
                if (arr[j + 1] < arr[j]) {
                    var change = arr[j + 1];
                    arr[j + 1] = arr[j];
                    arr[j] = change
                }
            }
        }
        var str = "";
        for (var i = 0; i < arr.length; i++) {
            str += arr[i]
        }
        $(".tips .rightDown").val(str);
    }
});